/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.saar.penguin.give2.mapviewer.notification;

import de.saar.basic.Pair;
import de.saar.penguin.give2.mapviewer.JMapViewer;
import de.saar.penguin.give2.mapviewer.MapAnnotationPlugin;
import java.awt.Graphics2D;
import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author koller
 */
public class NotificationPlugin implements MapAnnotationPlugin {
    private static final int CHECKING_INTERVAL = 1000; // ms
    protected JMapViewer viewer;
    final private Queue<Pair<Long, Drawable>> annotations;
    private Thread annotationCleanupThread;

    // TODO: sort by expiry time

    public NotificationPlugin(JMapViewer viewer) {
        this.viewer = viewer;
        annotations = new LinkedList<Pair<Long, Drawable>>();

        annotationCleanupThread = new CleanupThread();
        annotationCleanupThread.start();
    }

    public void addAnnotation(Drawable drawable, long lifespan) {
        annotations.add(new Pair(System.currentTimeMillis() + lifespan, drawable));
    }

    public void paint(Graphics2D graphics, JMapViewer viewer) {
        for (Pair<Long, Drawable> annotation : annotations) {
            annotation.right.draw(graphics);
        }
    }

    protected void clear() {
        synchronized (annotations) {
            annotations.clear();
        }
    }

    private class CleanupThread extends Thread {
        @Override
        public void run() {
            try {
                do {
                    boolean removedSomething = false;
                    boolean iterateAgain = true;

                    synchronized (annotations) {
                        while (iterateAgain) {
                            Pair<Long, Drawable> entry = annotations.peek();

                            if (entry == null) {
                                iterateAgain = false;
                            } else {
                                if (System.currentTimeMillis() >= entry.left) {
                                    annotations.poll();
                                    iterateAgain = true;
                                    removedSomething = true;
                                } else {
                                    iterateAgain = false;
                                }
                            }
                        }
                    }

                    if (removedSomething) {
                        viewer.repaint();
                    }

                    Thread.sleep(CHECKING_INTERVAL);
                } while (!interrupted());
            } catch (InterruptedException ex) {
            }
        }
    }
}
